<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0px;
        top: 0px;
      }
    </style>
  </head>

  <body>
    <div class="box"></div>
  </body>
</html>
<script>
  function move(boxEle, dir, dis, cb) {
    // 用来做settimeout的递归循环的函数
    function fn() {
      setTimeout(function () {
        var num = parseInt(getComputedStyle(boxEle)[dir]);
        var res = dis > num ? 1 : -1;
        var speed = 5 * res;
        boxEle.style[dir] = num + speed + "px";
        if (num + speed == dis) {
          cb && cb();
        } else {
          fn();
        }
      }, 10);
    }
    fn();
  }
  var boxEle = document.querySelector(".box");
  move(boxEle, "left", 300, function () {
    console.log("运动完成111");
    move(boxEle, "top", 400, function () {
      console.log("运动完成2222");
      move(boxEle, "left", 0, function () {
        console.log("运动完成3333");
        move(boxEle, "top", 0, function () {
          console.log("运动结束");
        });
      });
    });
  });
</script>
